package com.lv.service.dialog

import android.Manifest
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.text.TextUtils
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.lv.common.dialog.HintDialog
import com.lv.common.imp.OnPositionTListener
import com.lv.common.utils.CodeUtil
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.SaveImageUtils
import com.lv.common.utils.showToast
import com.lv.service.R
import com.lxj.xpopup.core.CenterPopupView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class ShowCodeBorderPopupView(
    private val mContext: Context,
    private val mCopeString: String,
    private val mLogo: String,
    private val mPositionTListener: OnPositionTListener<String>? = null
) :
    CenterPopupView(mContext) {
    private var mSaveBitmap: Bitmap? = null
    private var mCodeBitmap: Bitmap? = null
    private var mClCode: ConstraintLayout? = null

    //    private var mCopeString: String = ""
    override fun getImplLayoutId(): Int {
        return R.layout.show_code_border_popup
    }

    override fun onCreate() {
        super.onCreate()
        val ivCode = findViewById<ImageView>(R.id.iv_code)
        val ivClose = findViewById<ImageView>(R.id.iv_close)
        val ivLogo = findViewById<ImageView>(R.id.iv_logo)
        mClCode = findViewById<ConstraintLayout>(R.id.cl_code)
//        val deCodeUrl = URLEncoder.encodeWithUtf8(mTitle)
        lifecycleScope.launchWhenCreated {
//            val taskDesInfo = async {
//                mCopeString = getDesCode()
//            }
//            taskDesInfo.await()
            val taskCodeInfo = async {
                mCodeBitmap = getCodeBitmap()
            }
            taskCodeInfo.await()
            Glide.with(mContext).asBitmap().load(mLogo).into(ivLogo)
            Glide.with(mContext).load(mCodeBitmap).into(ivCode)

        }
        mClCode?.setOnLongClickListener {
            checkPermissions()
            return@setOnLongClickListener false
        }
        ivClose.setOnClickListener { dismiss() }

        initView()
        initEvnet()
    }


    private suspend fun getCodeBitmap(): Bitmap? {

        val bitmap = withContext(Dispatchers.IO) {
            getBitmap(mCopeString)
        }
        return bitmap
    }

    private suspend fun getViewBitmap(): Bitmap? {
        val bitmap = withContext(Dispatchers.Default) {
            SaveImageUtils.getViewGroupBitmapNoBg(mClCode)
        }
        return bitmap
    }

    private fun checkPermissions() {
        val permissions = mutableListOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
        )
        PermissionXUtils.checkPermissBefore(
            context as FragmentActivity, permissions, "您需要授予存储权限才能保存二维码到相册",
            object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        showHintDialog()
                    }
                }

                override fun fotPermsission() {
                    showToast("您需要授予存储权限才能保存二维码到相册")
                }
            },
        )
    }

    private var mHintDialog: HintDialog? = null
    private fun showHintDialog() {
        mHintDialog = HintDialog(mContext, "提示", "是否保存到相册", true, true, {
            startSave()
        })
        mHintDialog?.show()
    }

    private fun startSave() {
        mSaveBitmap = SaveImageUtils.getViewGroupBitmapNoBg(mClCode)
        SaveImageUtils.savePicToPhone(mContext, mSaveBitmap) {
            showToast("图片保存成功,请到相册查找")
        }
    }

    private fun initView() {

//        tvTitle?.text = mTitle


    }

    private fun initEvnet() {


    }

    private suspend fun getBitmap(deCodeUrl: String): Bitmap {
        return CodeUtil.createImage(
            deCodeUrl,
            SizeUtils.dp2px(197.0f),
            SizeUtils.dp2px(197.0f)
        )
    }

    private suspend fun setBitmap(imageView: ImageView) {
        (context as Activity).runOnUiThread {
            imageView.setImageBitmap(mCodeBitmap)
        }
    }

    private suspend fun getNotificationBitmapFromCache(url: String?): Bitmap? {
        if (TextUtils.isEmpty(url)) {
            return null
        }
//        val resultBitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565)
//        resultBitmap.eraseColor(Color.WHITE)
//        // 使用空白图片生成canvas
//        val canvas = Canvas(resultBitmap)
//        //第一步先把原图全部画上去
//        //源图-尺寸
//        val srcRect = Rect(0, 0, 100, 100)
//        //目标-位置
//        val dstRect = Rect(0, 0, 90, 90)
        var cachedBitmap: Bitmap? = null
        try {
            cachedBitmap = Glide.with(mContext).asBitmap().load(url).apply(
                RequestOptions().centerCrop().circleCrop().override(100, 100)
            ).submit()[500, TimeUnit.MILLISECONDS] // 最大等待200ms
//            canvas.drawBitmap(cachedBitmap, srcRect, dstRect, null)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return cachedBitmap
    }

    private fun setDismissDialog() {
        dismiss()
    }


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun beforeDismiss() {
        super.beforeDismiss()
        if (mHintDialog?.isShowing == true) {
            mHintDialog?.dismiss()
        }
        mCodeBitmap = null
        mSaveBitmap = null
    }

}